<template>
  <div class="r-content">
    <h3>欢迎来到李耳的博客</h3>

    <div class="block">
      <el-avatar :size="50" :src="user.avatar"></el-avatar>
      <div><h4>{{ user.username }}</h4></div>
    </div>

    <div class="r-action">
      <span><el-link @click="blogs">主页</el-link></span>
      <el-divider direction="vertical"></el-divider>
      <span><el-link type="success" @click="blog_edit">发表博客</el-link></span>

      <el-divider direction="vertical"></el-divider>
      <span v-show="!hasLogin"><el-link type="primary" @click="login">登录</el-link></span>
      <span v-show="hasLogin"><el-link type="danger" @click="logout">退出</el-link></span>
    </div>


  </div>
</template>

<script>
export default {
  name: "Header",
  data() {
    return {
      user: {
        username: '请先登录',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      },
      hasLogin:false,
    }
  },
  methods: {
    //退出方法
    logout() {
      var _this = this;
      //后端需要认证，所以添加上token信息
      _this.$axios.get("/logout", {
        headers: {
          "Authorization": localStorage.getItem('token')
        }
      }).then(res => {
        _this.$store.commit('REMOVE_INFO');
        _this.$router.push({name: 'Login'});
      })
    },
    blog_edit(){
      this.$router.push({name: 'BlogEdit'});
    },
    blogs(){
      this.$router.push({name: 'Blogs'});
    },
    login(){
      this.$router.push({name: 'Login'});
    }

  },
  created() {
    //如果页面加载时有用户信息的话
    if (this.$store.state.userInfo.username){
      this.user.username = this.$store.state.userInfo.username;
      this.user.avatar = this.$store.state.userInfo.avatar;
      this.hasLogin = true
    }
  }
}
</script>

<style scoped>
.r-content {
  max-width: 960px;
  margin: 0 auto;
  text-align: center;
}

.r-action {
  margin: 10px 0;
}
</style>
